#include<stdlib.h>
#include<stdio.h>
#include<string.h>

#include"list_queue.h"

int list_queue_dequeue(list_queue *queue,int *data);


list_queue *list_queue_create()
{
	list_queue *queue = NULL;
	queue = (list_queue *)malloc(sizeof(list_queue));
	if(queue == NULL)
		return NULL;

	queue->num = 0;
	queue->head = NULL;
	queue->tail = NULL;

	return queue;
}

void list_queue_destory(list_queue *queue)
{
	int i = 0;
	int data = 0;

	if((queue == NULL) ||(list_queue_is_empty(queue)))
		return;

	while(!list_queue_is_empty(queue))
	{
		(void)list_queue_dequeue(queue,&data);
		printf("dequeue data=%d\n",data);
	}
	free(queue);
	return;
}

int list_queue_enqueue(list_queue *queue,int data)
{
	queue_node *ptmp =  NULL;
	if(queue == NULL)
	{
		printf("queue enqueue is NULL\n");
		return -1;
	}
	ptmp = (queue_node *)malloc(sizeof(queue_node));
	if(ptmp == NULL)
	{
		printf("malloc queue node error\n");
		return -1;
	}
	ptmp->data = data;
	ptmp->next = NULL;
	
	if(queue->head == NULL)
		queue->head = ptmp;
	else
		queue->tail->next = ptmp;

	queue->tail = ptmp;
	queue->num++;

	return 0;
}

int list_queue_dequeue(list_queue *queue,int *data)
{
	queue_node *ptmp = NULL;

	if((queue == NULL) || (data == NULL)||list_queue_is_empty(queue))
	{
		printf("de queue is null or list queue is empty\n");
		return -1;
	}
	*data = queue->head->data;
	ptmp = queue->head;
	queue->num--;
	queue->head = queue->head->next;
	if(queue->head == NULL)
		queue->tail =  NULL;

	free(ptmp);
	return 0;
}

void list_queue_dump(list_queue *queue)
{
	int i=0;
	queue_node *ptmp;
	if((ptmp == NULL) || (list_queue_is_empty(queue)))
	{
		printf("dump queue is NULL or empty\n");
		return;
	}
	ptmp = queue->head;

	while(ptmp != NULL)
	{
		printf("node[%d]=%d\n",i,ptmp->data);
		i++;
		ptmp = ptmp->next;
	}
	printf("--------------------------\n");

	return ;
}

int main()
{
	int i=0;
	int data = 0;
	int ret = 0;

	list_queue *queue;
	queue = list_queue_create();
	if(queue == NULL)
	{
		printf("list queue create failed\n");
		return 0;
	}

	printf("list queue ok\n");
	for(i =0;i<5;i++)
	{
		list_queue_enqueue(queue,i);
	}

	list_queue_dump(queue);

	ret = list_queue_dequeue(queue,&data);
	if(ret != 0)
	{
		printf("queue dequeue failed =%d\n",ret);
	}
	printf("dequeue data=%d\n",data);
	list_queue_dump(queue);

	list_queue_destory(queue);
	return 0;

}
